package com.thrc.borrow.controller;

import java.io.IOException;
import java.util.List;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.thrc.borrow.entity.User;
import com.thrc.borrow.service.CityService;
import com.thrc.borrow.service.SmsService;
import com.thrc.borrow.service.UserService;
import com.thrc.borrow.utils.MsgType;
import com.thrc.borrow.utils.ResponseUtil;
import com.thrc.borrow.utils.ReturnCode;
import com.thrc.borrow.vo.CityVo;
import com.thrc.borrow.vo.UserVo;

@Controller
@RequestMapping("/util")
public class UtilController {

	@Autowired
	private UserService userService;
	@Autowired
	private CityService cityService;
	@Autowired
	private SmsService smsService;

	/**
	 * 发送验证码
	 * 
	 * @param phone
	 * @param request
	 */
	@RequestMapping("/sms/send")
	public void sendSMS(@RequestParam("phone") String phone, @RequestParam("imgCode") String imgCode,
			HttpServletResponse response, HttpServletRequest request) {
		try {
			if (StringUtils.isBlank(phone)) {
				ResponseUtil.print(response, ReturnCode.FAIL_CODE, "手机号不能为空");
				return;
			}
			if (userExistsByPhone(phone)) {
				ResponseUtil.print(response, ReturnCode.FAIL_CODE, "手机号已存在");
				return;
			}
			if (StringUtils.isBlank(imgCode)) {
				ResponseUtil.print(response, ReturnCode.FAIL_CODE, "图形验证码不能为空");
				return;
			}
			String session_code = (String) request.getSession().getAttribute("jcaptchaCode");
			if (!imgCode.equalsIgnoreCase(session_code)) {
				ResponseUtil.print(response, ReturnCode.FAIL_CODE, "图形验证码错误");
				return;
			}
			String code = randomCode();
			System.out.println("-----------------注册验证码为:" + code);
			request.getSession().setAttribute("reg_code", code);

			smsService.sendCaptchaCodeSms(phone, code, MsgType.REGISTER);

			ResponseUtil.print(response, ReturnCode.SUCCESS_CODE);

		} catch (Exception e) {
			ResponseUtil.print(response, ReturnCode.ERROR_CODE);
		}
	}

	@RequestMapping("/code/check")
	public String checkCode(@RequestParam("code") String code, HttpServletRequest request, HttpServletResponse response)
			throws IOException {

		Object sessionCode = request.getSession().getAttribute("reg_code");
		if (code.equals(sessionCode)) {
			ResponseUtil.print(response, ReturnCode.SUCCESS_CODE);
		} else if (sessionCode == null) {
			ResponseUtil.print(response, ReturnCode.FAIL_CODE, "请发送验证码");
		} else {
			ResponseUtil.print(response, ReturnCode.FAIL_CODE, "验证码输入不正确");
		}

		return null;
	}

	/**
	 * 发送找回密码验证码
	 * 
	 * @param phone
	 * @param request
	 */
	@RequestMapping("/sms/send/findPwd")
	public void sendSMSFindPwd(@RequestParam("phone") String phone, HttpServletResponse response,
			HttpServletRequest request) {
		try {
			if (StringUtils.isBlank(phone)) {
				ResponseUtil.print(response, ReturnCode.FAIL_CODE, "手机号不能为空");
				return;
			}
			if (!(userExistsByPhone(phone))) {
				ResponseUtil.print(response, ReturnCode.FAIL_CODE, "手机号不存在");
				return;
			}
			String code = randomCode();
			System.out.println("-----------------找回密码验证码为:" + code);
			request.getSession().setAttribute("findPwd_code", code);

			smsService.sendCaptchaCodeSms(phone, code, MsgType.FORGET_PWD);

			ResponseUtil.print(response, ReturnCode.SUCCESS_CODE);

		} catch (Exception e) {
			ResponseUtil.print(response, ReturnCode.ERROR_CODE);
		}
	}

	@RequestMapping("/code/check/findPwd")
	public void checkCodeFindPwd(@RequestParam("code") String code, HttpServletRequest request,
			HttpServletResponse response) throws IOException {

		Object sessionCode = request.getSession().getAttribute("findPwd_code");
		if (code.equals(sessionCode)) {
			ResponseUtil.print(response, ReturnCode.SUCCESS_CODE);
		} else if (sessionCode == null) {
			ResponseUtil.print(response, ReturnCode.FAIL_CODE, "请发送验证码");
		} else {
			ResponseUtil.print(response, ReturnCode.FAIL_CODE, "验证码输入不正确");
		}
	}

	@RequestMapping("/province/get")
	public String getProvince(HttpServletRequest request, HttpServletResponse response) throws IOException {
		List<CityVo> list = cityService.getProvince();
		ResponseUtil.print(response, list);
		return null;
	}

	@RequestMapping("/city/get")
	public String getCity(@RequestParam(value = "pid") Integer pid, HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		List<CityVo> list = cityService.getCity(pid);
		ResponseUtil.print(response, list);
		return null;
	}

	/**
	 * 根据手机号判断用户是否存在，存在返回true
	 * 
	 * @param phone
	 *            用户手机号
	 * @return
	 */
	public boolean userExistsByPhone(String phone) {
		User t = new User();
		t.setPhone(phone);
		UserVo userCheck = userService.selectByPhone(t);
		return userCheck == null ? false : true;
	}

	public String randomCode() {
		// 随机产生4位数字
		int intCount = 0;
		intCount = (new Random()).nextInt(9999);// 最大值位9999
		if (intCount < 1000) {
			intCount += 1000; // 最小值位1001
		}
		return intCount + "";
	}
}
